﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//加农炮
public class Cannon : Weapon {

	// public float timer = 0;
	// public bool trigger = false;//标记是敌人还是玩家的子弹
	public float distance = 0;//射出距离
	public bool isAttack = false;//子弹是否是攻击状态
	public bool isInPool = true;//是否在对象池里面
	// public Rigidbody2D rb;

	/// <summary>
	/// Start is called on the frame when a script is enabled just before
	/// any of the Update methods is called the first time.
	/// </summary>
	void Start()
	{
		// ShowSelf();
		// rb = this.GetComponent<Rigidbody2D>();
	}
	 
	// Update is called once per frame
	void Update () {
		if(isAttack)
		{
			timer += Time.deltaTime;
			distance = speed * timer;

			// 超出攻击范围就销毁
			if(distance > attackDistance)
			{
//				print("超出攻击范围");
				StoreInPool();
			}
			// 子弹移动
			transform.Translate(new Vector3(0, speed * Time.deltaTime, 0));
			// rb.velocity = transform.up * speed;
		}	
	}

	


	void OnTriggerEnter2D(Collider2D collision)
	{
		if(trigger)
		{
			// 子弹碰到敌人
			if(collision.tag == "Enemy")
			{
				if(!isInPool)
				{
//					print("碰到敌人");
					collision.gameObject.SendMessage("TakeDamage", damage);
					StoreInPool();
					isInPool = true;
					
				}
			}
		}
		else
		{
			// 子弹碰到hero
			if(collision.tag == "Hero")
			{
				if(collision.gameObject != null)
				{
					print("碰到hero");
					collision.gameObject.SendMessage("TakeDamage", damage);
					StoreInPool();
					isInPool = true;
					
				}
			}
		}
	}

	
	void OnTriggerStay2D(Collider2D collision)
	{
		if(trigger)
		{
			// 子弹碰到敌人
			if(collision.tag == "Enemy")
			{
				if(!isInPool)
				{
					print("碰到敌人");
					collision.gameObject.SendMessage("TakeDamage", damage);
					StoreInPool();
					isInPool = true;
					
				}
			}
		}
		else
		{
			// 子弹碰到hero
			if(collision.tag == "Hero")
			{
				if(collision.gameObject != null)
				{
					print("碰到hero");
					collision.gameObject.SendMessage("TakeDamage", damage);
					StoreInPool();
					isInPool = true;
					
				}
			}
		}
	}


	// 达到销毁条件的时候，对象池回收
	void StoreInPool()
	{
		isAttack = false;
		transform.position = new Vector3(1000, 1000, 0);
		timer = 0;
		distance = 0;
		PoolControl.instance.cannonPool.Store(gameObject);
		
	}
}
